package com.bruip.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bruip.reggie.common.CustomException;
import com.bruip.reggie.mapper.CategoryMapper;
import com.bruip.reggie.pojo.Category;
import com.bruip.reggie.pojo.Dish;
import com.bruip.reggie.pojo.Setmeal;
import com.bruip.reggie.service.CategoryService;
import com.bruip.reggie.service.DishService;
import com.bruip.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 王若龙
 * @date 2022-10-06 16:48
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private SetmealService setmealServer;

    @Autowired
    private DishService dishService;

    @Override
    public void removeCategoryById(Long id) {

        //1.判断是否关联菜品，是则抛出业务异常
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId, id);
        int dishCount = dishService.count(dishLambdaQueryWrapper);
        if (dishCount > 0){
            // 关联了菜品，抛出业务异常
            throw new CustomException("当前分类下关联了菜品，不能删除");
        }

        //2.判断是否关联套餐，是则抛出异常
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, id);
        int seMealCount = setmealServer.count(setmealLambdaQueryWrapper);
        if (seMealCount > 0){
            // 关联了套餐，抛出业务异常
            throw new CustomException("当前分类下关联了套餐，不能删除");
        }
        //3.如果都没有关联，则执行删除
        super.removeById(id);
    }
}
